#!/usr/bin/env node
const http = require('http'),
      url  = require('url'),
      qs   = require('querystring'),
      log  = console.log,
      fs = require('fs');
let items=['EAT','SLEEP'];
function getPage(){
  let html = fs.readFileSync('./tmplate.html').toString('utf8');

  html = html.replace('*',items.map(i => '<li>' + i + '</li>').join('\n'));
  console.log(html);
return html;
}

http.createServer((req,res)=>{
if(req.url!=='/'){
res.statusCode = 404;
res.setHeader('Content-Length', 'text/html');
res.setHeader('Content-Type', 'text/plain');
return;
}
let data ='';
req.on('data',chunk=>data+=chunk);

req.on('end',()=>{
  let item = qs.parse(data).item;


if(item !== '' && typeof item !=='undefined'){
    items.push(item)
}

  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Content-Length', Buffer.byteLength(getPage()));             
  res.statusCode = 200;
  res.end(getPage());

})
}).listen(8080);
